package com.wenhai.spring.bean.scope;

import com.wenhai.xiaomage.spring.ioc.overview.dependency.domain.User;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

/**
 * @Author:wenhai
 * @Description: Spring Bean Scope
 * @Date:2020/3/15
 */
public class BeanThreadLocalScopeDemo {


    @Bean
    @Scope(ThreadLocalScope.THREAD_LOCOL)
    public static User user() {
        return createUser();
    }


    private static User createUser() {
        User user = new User();
        user.setId(System.currentTimeMillis());
        return user;
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext cxt = new AnnotationConfigApplicationContext();
        cxt.addBeanFactoryPostProcessor(beanFactory -> beanFactory.registerScope(ThreadLocalScope.THREAD_LOCOL, new ThreadLocalScope()));
        cxt.register(BeanThreadLocalScopeDemo.class);
        cxt.refresh();
        scopedBeansForLookup(cxt);
        cxt.close();
    }



    private static void scopedBeansForLookup(AnnotationConfigApplicationContext cxt) {
        for (int i = 0; i < 3; i++) {
           new Thread(() -> {
                User user = cxt.getBean("user", User.class);
                System.out.printf("CurrentThreadId:%d,user:%s%n",Thread.currentThread().getId(),user);
            }).start();

        }
    }
}
